﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
 
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Skipette
{
    public partial class FormMain : Form, BaseMain
    {
        Startup st;
        Conversation currentConversation;
        bool safeClose;
        String lastCategory = "";

        public FormMain(Startup st)
        {
            CheckForIllegalCrossThreadCalls = false;
            this.st = st;
            InitializeComponent();
            comboBoxCat.SelectedIndex = 0;
            richTextBoxWrite.GotFocus += new EventHandler(richTextBoxWrite_GotFocus);
            richTextBoxWrite.LostFocus += new EventHandler(richTextBoxWrite_LostFocus);
            this.FormClosed += new FormClosedEventHandler(FormMain_FormClosed);
            this.labelName.Text = Program.currentProfile.firstName;
            this.labelStatus.Text = Program.currentStatus.ToString();
            this.textBoxStatus.Text = Program.currentProfile.statusMessage;

            Conversation c = new Conversation(); //dummy
            Program.conversations.Add(c); //dummy
            ChangeConversation(c);//dummy

            textBoxStatus.GotFocus += new EventHandler(textBoxStatus_GotFocus);
            textBoxStatus.LostFocus += new EventHandler(textBoxStatus_LostFocus);
            comboBoxCat.SelectedIndex = 0;
        }

        void textBoxStatus_LostFocus(object sender, EventArgs e)
        {
            this.AcceptButton = buttonEnter;
            this.CancelButton = null;
        }

        void textBoxStatus_GotFocus(object sender, EventArgs e)
        {
            this.AcceptButton = buttonConfirmStatus;
            this.CancelButton = buttonCancelStatus;
        }

        void FormMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (!safeClose)
                st.Close();
            safeClose = false;
        }

        void richTextBoxWrite_LostFocus(object sender, EventArgs e)
        {
            this.AcceptButton = null;
        }

        void richTextBoxWrite_GotFocus(object sender, EventArgs e)
        {
            this.AcceptButton = buttonEnter;
        }

        //FOR BLINKING CONTROLS
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;  // Turn on WS_EX_COMPOSITED
                return cp;
            }
        }


        public void ChangeConversation(Conversation changeTo)
        {

            currentConversation = changeTo;
            if (!changeTo.video)
            {

            }
            else
            {

            }
        }


        private void pictureProfile_Click(object sender, EventArgs e)
        {
            ProfileView profWindow = new ProfileView();
            profWindow.Show();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            st.Close();
        }

        private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            st.Logout();
        }

        private void busyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            st.SetIcoStatus("Busy");
        }

        private void onlineToolStripMenuItem_Click(object sender, EventArgs e)
        {
            st.SetIcoStatus("Online");
        }

        private void hiddenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            st.SetIcoStatus("Hidden");
        }

        private void buttonVideo_Click(object sender, EventArgs e)
        {

        }

        private void buttonCall_Click(object sender, EventArgs e)
        {
            //CALL MECHANICS HERE
            buttonCall.Hide();
            buttonHangUp.Show();
        }

        private void buttonHangUp_Click(object sender, EventArgs e)
        {
            //HANG UP MECHANICS HERE
            buttonCall.Show();
            buttonHangUp.Hide();
        }

        private void buttonEnter_Click(object sender, EventArgs e)
        {
            //SEND MESSAGE MECHANICS HERE
            currentConversation.SendMessage(Program.currentProfile, richTextBoxChat, richTextBoxWrite.Text);
            richTextBoxWrite.Text = "";
        }

        private void buttonCategory_Click(object sender, EventArgs e)
        {

        }

        private void buttonEmo_Click(object sender, EventArgs e)
        {
            if (panelEmoticons.Visible)
                panelEmoticons.Hide();
            else
                panelEmoticons.Show();
        }

        private void LoadContacts(List<Account> contacts)
        {
            foreach (Account contact in contacts)
            {
                listViewContacts.Items.Add(new ListViewItem(contact.firstName + " " + contact.surname + " " + "(" + contact.username + ")"));
            }
        }

        public void AddCategory(String catName)
        {
            comboBoxCat.Items.Insert(1, catName);
            comboBoxCat.SelectedItem = catName;
        }

        private void comboBoxCat_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxCat.SelectedIndex == 0)
            {
                LoadContacts(Program.contacts);
            }
            if (comboBoxCat.SelectedIndex == comboBoxCat.Items.Count - 1)
            {
                NewCat newCatWindow = new NewCat(this);
                newCatWindow.Show();
                comboBoxCat.SelectedItem = lastCategory;
                return;
            }
            else
            {
                if (!lastCategory.Equals(comboBoxCat.SelectedItem.ToString()))
                {
                    foreach (Category c in Program.categories)
                    {
                        if (c.name.Equals(comboBoxCat.SelectedItem.ToString()))
                        {
                            LoadContacts(c.contacts);
                            break;
                        }
                    }
                }
            }
            lastCategory = comboBoxCat.SelectedItem.ToString();
        }

        private void compactViewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormCompact compactWindow = new FormCompact(st);
            compactWindow.Show();
            st.main = compactWindow;
            safeClose = true;
            this.Close();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void pictureFriendProfile_Click(object sender, EventArgs e)
        {
            ProfileView profWindow = new ProfileView(labelFriendUname.Text);
            profWindow.Show();
        }

        public void UpdateStatuses()
        {
            labelStatus.Text = Program.currentStatus.ToString();
            if (labelStatus.Text.Equals("ONLINE"))
                pictureBoxStatus.BackgroundImage = Properties.Resources.online;
            else if (labelStatus.Text.Equals("BUSY"))
                pictureBoxStatus.BackgroundImage = Properties.Resources.busy;
            else if (labelStatus.Text.Equals("HIDDEN"))
                pictureBoxStatus.BackgroundImage = Properties.Resources.hidden;
            else
                pictureBoxStatus.BackgroundImage = Properties.Resources.offline;
            labelFriendStatus.Text = Server.GetAccount(labelFriendUname.Text.Split(new String[] { "Username: " }, StringSplitOptions.None)[1]).currentStatus.ToString();
        }

        public void SetSafeClose(bool safe)
        {
            this.safeClose = safe;
        }

        public bool IsVisible()
        {
            return this.Visible;
        }

        private void textBoxStatus_TextChanged(object sender, EventArgs e)
        {

        }


        public void ShowMessage(int convId, string authUserName, string dateTime, string message)
        {
            String authName = "";
            if (Program.currentProfile.username.Equals(authUserName))
                authName = Program.currentProfile.firstName;
            else
                foreach (Account fr in Program.currentProfile.friends)
                {
                    if (fr.username.Equals(authUserName))
                    {
                        authName = fr.firstName;
                    }
                }
            if (currentConversation.convId == convId)
            {
                int lastPos = richTextBoxChat.Text.Length;
                richTextBoxChat.AppendText("\n" + authName + " (" + authUserName + ") " + dateTime);
                richTextBoxChat.AppendText("\n  " + message + "\n");
                if (authUserName.Equals(Program.currentProfile.username))
                    HighlightPhrase(richTextBoxChat, lastPos, authName, Color.DodgerBlue, true);
                else
                    HighlightPhrase(richTextBoxChat, lastPos, authName, Color.Orange, true);
                HighlightPhrase(richTextBoxChat, lastPos, dateTime, Color.Black, true);
            }
        }


        private void HighlightPhrase(RichTextBox box, int pos, string phrase, Color color, bool bold)
        {
            //int pos = box.SelectionStart;
            box.SelectionStart = pos;
            string s = box.Text;
            for (int ix = 0; ; )
            {
                int jx = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase);
                if (jx < 0) break;
                box.SelectionStart = jx;
                box.SelectionLength = phrase.Length;
                box.SelectionColor = color;
                if (bold)
                    box.SelectionFont = new Font(box.Font, FontStyle.Bold);
                ix = jx + 1;
            }
            //box.SelectionStart = pos;
            box.SelectionLength = 0;
        }

        private void buttonConfirmStatus_Click(object sender, EventArgs e)
        {
            Program.currentProfile.statusMessage = textBoxStatus.Text;
            Server.UpdateStatusMessage(Program.currentProfile, Program.currentProfile.statusMessage);
            textBoxStatus.SelectAll();
            ShowUpdateStatusMessageConfirmation(1000);
        }

        private void ShowUpdateStatusMessageConfirmation(int millisec)
        {
            Thread updater = new Thread(delegate()
                {
                    labelUpdated.BeginInvoke((MethodInvoker)delegate { { labelUpdated.Show(); } });
                    Thread.Sleep(millisec);
                    labelUpdated.BeginInvoke((MethodInvoker)delegate { { labelUpdated.Hide(); } });
                }); updater.IsBackground = true; updater.Priority = ThreadPriority.BelowNormal; updater.Start();
        }

        private void buttonCancelStatus_Click(object sender, EventArgs e)
        {
            textBoxStatus.Text = Program.currentProfile.statusMessage;
        }
    }
}
